package com.region.http.client.resolver.result;

import com.region.common.utils.ReflectUtils;
import com.region.http.client.common.Constant;
import com.region.http.client.exception.NotFoundResultResolverException;
import com.region.http.client.model.ResponseData;

import java.lang.reflect.Type;

/**
 * Eight basic data type result parsers, less efficient if using JSON adapters, 50-100 times more efficient using basic type converters
 *
 * @author liujieyu
 * @date 2022/12/2
 */
public class BasicResultResolver extends AbstractResultResolver {

    @Override
    public boolean isResolver(Type type) {
        Class<?> returnClass = ReflectUtils.transform(type);
        return int.class.isAssignableFrom(returnClass) || float.class.isAssignableFrom(returnClass) || double.class.isAssignableFrom(returnClass) || long.class.isAssignableFrom(returnClass) || byte.class.isAssignableFrom(returnClass) || char.class.isAssignableFrom(returnClass) || boolean.class.isAssignableFrom(returnClass) || short.class.isAssignableFrom(returnClass);
    }

    @Override
    public Object resolver(ResponseData responseData) throws Throwable {
        String resultStr = new String(responseData.getBody());
        Class<?> returnClass = ReflectUtils.transform(responseData.getType());
        if (int.class.isAssignableFrom(returnClass)) {
            return Integer.parseInt(resultStr);
        } else if (float.class.isAssignableFrom(returnClass)) {
            return Float.parseFloat(resultStr);
        } else if (double.class.isAssignableFrom(returnClass)) {
            return Double.parseDouble(resultStr);
        } else if (long.class.isAssignableFrom(returnClass)) {
            return Long.parseLong(resultStr);
        } else if (byte.class.isAssignableFrom(returnClass)) {
            return Byte.parseByte(resultStr);
        } else if (char.class.isAssignableFrom(returnClass)) {
            // char类型取第二位， 第一位是 ""
            return resultStr.toCharArray()[1];
        } else if (boolean.class.isAssignableFrom(returnClass)) {
            return Boolean.parseBoolean(resultStr);
        } else if (short.class.isAssignableFrom(returnClass)) {
            return Short.parseShort(resultStr);
        } else {
            throw new NotFoundResultResolverException("Not Found Result Resolver");
        }
    }

    @Override
    public int getPriority() {
        return Constant.MIN_ORDER;
    }
}
